package com.tiance.web.controller.front;

import com.alibaba.fastjson.JSON;
import com.tiance.constants.CommonConstants;
import com.tiance.dal.dataobject.TcDutyDO;
import com.tiance.domainservice.checker.ActivityChecker;
import com.tiance.domainservice.checker.DutyChecker;
import com.tiance.domainservice.checker.MeetingRoomChecker;
import com.tiance.domainservice.domain.DutyDomain;
import com.tiance.domainservice.domain.DutyDomain;
import com.tiance.domainservice.service.ActivityService;
import com.tiance.domainservice.service.DutyService;
import com.tiance.enums.*;
import com.tiance.exception.BusinessException;
import com.tiance.integration.cache.MapCacheUtil;
import com.tiance.page.QueryPage;
import com.tiance.utils.BeanConverterUtil;
import com.tiance.vo.DutyVO;
import com.tiance.vo.DutyVO;
import com.tiance.web.aspect.OperatorControllerLog;
import com.tiance.web.controller.base.FrontController;
import com.tiance.web.controller.common.BaseResponse;
import com.tiance.web.convertor.ModelConvert;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author hmz
 * @version 1.0.0
 * @date$ 2019/1/30
 *
 * Description：值班
 *
 * Modification History:
 *
 */
@Controller
@RequestMapping(value = "/front/duty")
public class DutyController extends FrontController{

    private static String LOG_PREFIX ="DutyController| 值班控制器===>";

    @Autowired
    private DutyService dutyService;


    @RequestMapping(value = "/toAppwork.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到值班页面")
    public String toAppwork() {
        return "/front/appwork";

    }

    @RequestMapping(value = "/toAppmeet.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到值班页面")
    public String toAppmeet() {
        return "/front/appmeet";

    }

    @RequestMapping(value = "/toAppworktime.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到值班页面")
    public String toAppworktime() {
        return "/front/appworktime";

    }

    @RequestMapping(value = "/toCommunitywork.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到值班页面")
    public String toCommunitywork() {
        return "/front/communitywork";

    }
    @RequestMapping(value = "/cancelDuty.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="取消值班")
    public BaseResponse cancel(DutyVO dutyVO){
        logger.info("开始取消值班，请求参数:{}", JSON.toJSONString(dutyVO));
        BaseResponse backResponse=new BaseResponse<>();

        try {
            DutyChecker.checkCancelDuty(dutyVO);
            DutyDomain dutyDomain= ModelConvert.dutyVO2DutyDomain(dutyVO);
            if(MapCacheUtil.lock(dutyVO.getId() + EntityTypeEnum.DUTY_APPLICANT.getCode())) {
                dutyService.cancel(dutyDomain);
                backResponse.setQueryPage(dutyDomain.getQueryPage());
                backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
                backResponse.setSuccess(true);
            }else {
                throw new BusinessException("该值班正在操作中，请稍后再试!");
            }
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"取消值班失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"取消值班失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("取消值班失败");
        }finally {
            MapCacheUtil.unlock(dutyVO.getId()+EntityTypeEnum.DUTY_APPLICANT.getCode());
        }
        logger.info("结束取消值班，返回数据:{}", JSON.toJSONString(backResponse));
        return backResponse;

    }



    @RequestMapping(value = "/finishDuty.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="结束值班")
    public BaseResponse finish(DutyVO dutyVO){
        logger.info("开始结束值班，请求参数:{}", JSON.toJSONString(dutyVO));
        BaseResponse backResponse=new BaseResponse<>();

        try {
            DutyChecker.checkCancelDuty(dutyVO);
            DutyDomain dutyDomain= ModelConvert.dutyVO2DutyDomain(dutyVO);
            if(MapCacheUtil.lock(dutyVO.getId()+EntityTypeEnum.DUTY_APPLICANT.getCode())) {
                dutyService.finish(dutyDomain);
                backResponse.setQueryPage(dutyDomain.getQueryPage());
                backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
                backResponse.setSuccess(true);
            }else {
                throw new BusinessException("该值班正在操作中，请稍后再试!");
            }
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"结束值班失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"结束值班失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("结束值班失败");
        }finally {
            MapCacheUtil.unlock(dutyVO.getId()+EntityTypeEnum.DUTY_APPLICANT.getCode());
        }
        logger.info("结束值班，返回数据:{}", JSON.toJSONString(backResponse));
        return backResponse;

    }



    @RequestMapping(value = "/addDuty.action",method = RequestMethod.POST)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="添加值班")
    public String addDuty(HttpServletRequest request, Model model, DutyVO dutyVO){
        logger.info("开始插入值班，请求参数:{}", JSON.toJSONString(dutyVO));

        try {
            HttpSession session=request.getSession();
            Object memberId=session.getAttribute(CommonConstants.MEMBER_ID);
            if(null!=memberId){
                dutyVO.setMemberId((Long)memberId);
                dutyVO.setApplicantId((Long)memberId);
            }
            DutyChecker.checkAddDuty(dutyVO);
            List<String> status = Arrays.asList(DutyStatusEnum.AUDIT_PASS.getCode(),DutyStatusEnum.ON_DUTY.getCode(),DutyStatusEnum.UN_AUDIT.getCode());
            dutyVO.setStatusScope(status);
            DutyDomain dutyDomain= ModelConvert.dutyVO2DutyDomain(dutyVO);
            dutyService.addDuty(dutyDomain);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"插入值班失败，失败原因：",e1);
            model.addAttribute("errorInfo","插入值班失败，请稍后重试!");
            return  "/views/initFail";
        }catch (Exception e2){
            model.addAttribute("errorInfo","插入值班失败,请稍后重试!");
            logger.error(LOG_PREFIX+"插入值班失败,失败原因",e2);
            return "/views/initFail";
        }
        logger.info("结束插入值班，返回数据:{}", model);
        return  "/views/initFail";

    }


    @RequestMapping(value = "/queryDutyApplyList.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询会员申请的值班列表")
    public BaseResponse queryDutyApplyList(DutyVO dutyVO, QueryPage queryPage){
        logger.info("开始查询会员申请值班，请求参数:{}", JSON.toJSONString(dutyVO));
        BaseResponse<TcDutyDO> backResponse=new BaseResponse<>();

        try {
            DutyChecker.checkPageQuery(queryPage);
            DutyDomain dutyDomain= ModelConvert.dutyVO2DutyDomain(dutyVO);
            dutyDomain.setQueryPage(queryPage);
            List<TcDutyDO> dutyDOList= dutyService.queryDuty(dutyDomain);
            backResponse.setResultList(dutyDOList);
            backResponse.setQueryPage(dutyDomain.getQueryPage());
            backResponse.setTotalRecord(dutyDOList.size());
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询会员申请值班失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"查询会员申请值班失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("查询会员申请值班失败");
        }
        logger.info("结束查询会员申请值班，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }

}